﻿using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using DG.Tweening;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using WssEvents;

namespace JQMergeFramework
{

    public enum UsePropTypes
    {
        None,
        Move,
        Remove,
    }

    public class ShowAddBuildTips
    {
        public float start = 0;
        public float end = 0;

        public ShowAddBuildTips(float _start, float _end)
        {
            start = _start;
            end = _end;
        }
    }


    public class UIGame : MonoBehaviour
    {
        public static UIGame I;

        [Header("星星特效")] public ParticleSystem starEffect;

        //关卡
        public Text oldLvTxt, newLvTxt;

        //增加楼层提示
        public Text showAddBuildTxt;

        //总分数
        public UIRollNumber scoreTxt;
        
        //总层数
        public UIRollNumber cityTotalNumTxt;
        public Text mainCityAddNumTips;
        
        //关卡进度
        public Image scoreFill;

        //增加层数提示
        public Transform addTBuildTips;

        public Text refreshNumTxt, discardTxt, clearNumTxt, moveNumTxt;
        public UISwitchChild refreshSwitch, clearSwitch, moveSwitch, discardSwitch;

        public Text allFinishAchievementNumTxt;
        
        //成就提示标签
        public Transform achievementFinishTag;
        public Text achievementFinishTxt;
        
        private List<ShowAddBuildTips> showAddInfo = new List<ShowAddBuildTips>()
        {
            new ShowAddBuildTips(0,0.2F),
            new ShowAddBuildTips(0.5F,0.7F),
            new ShowAddBuildTips(0.8F,1)
        };

        //展示增加层数提示ui显示记录
        private float showAddTipsNode;

        private float clickTime = 0;


        private void Update()
        {
            clickTime += Time.deltaTime;
        }


        private void Awake()
        {
            I = this;
            achievementFinishTag.gameObject.SetActive(false);
            UIManager.Instance.AddBtnListener(this.transform);
        }

        //展示成就标签
        public void ShowAchievementTag(CityTargetCfg  mCfg)
        {
            DOTween.Kill(achievementFinishTag.GetInstanceID());

            achievementFinishTag.gameObject.SetActive(true);
            achievementFinishTxt.text = string.Format("成就超越：<color=#fffc23>{0}</color>",mCfg.name);
            
            RectTransform tagRect = achievementFinishTag.GetComponent<RectTransform>();
            LayoutRebuilder.ForceRebuildLayoutImmediate(achievementFinishTxt.GetComponent<RectTransform>());
            LayoutRebuilder.ForceRebuildLayoutImmediate(tagRect);
            Vector3 startPos = new Vector3(138 + tagRect.rect.width, achievementFinishTag.localPosition.y, 0);

            achievementFinishTag.localPosition = startPos;
                
            
            Sequence sq = DOTween.Sequence().SetId(achievementFinishTag.GetInstanceID());
            
            sq.Append(achievementFinishTag.DOLocalMoveX(138, 1F).SetEase(Ease.OutQuad));
            sq.AppendInterval(2F);
            sq.Append(achievementFinishTag.DOLocalMoveX(startPos.x, 1F).SetEase(Ease.OutQuad));
            sq.OnComplete(() =>
            {
                achievementFinishTag.gameObject.SetActive(false);
            });
        }


        private void OnDisable()
        {
            GlobalEvent.Removelistener(GameEvents.OnRefreshScore, OnRefreshScore);
            GlobalEvent.Removelistener(GameEvents.OnRefreshProp, OnRefreshPropNum);
        }

        private void OnEnable()
        {
            GlobalEvent.Addlistener(GameEvents.OnRefreshScore, OnRefreshScore);
            GlobalEvent.Addlistener(GameEvents.OnRefreshProp, OnRefreshPropNum);
        }



        void OnBtnClick(Transform trans)
        {

            AudioManager.Instance.Play(AudioName.Click);


            if (InputManager.I.isNoRayClick)
            {
                return;
            }

            switch (trans.name)
            {
                case "BtnDiscardCity":
                    if (clickTime < 0.5f) return;
                    clickTime = 0;

                    if (DataManager.Instance.GetPropNum(PropId.DiscardProp) <= 0)
                    {
                        ShowReceivePropUI(PropId.DiscardProp);
                    }
                    else
                    {
                        //丢弃第一个建筑
                        MergeManager.Instance.DiscardCity();
                    }
                    break;
                case "BtnRemoveCity":
                    if (clickTime < 0.5f) return;

                    if (DataManager.Instance.GetPropNum(PropId.RemoveProp) <= 0)
                    {
                        ShowReceivePropUI(PropId.RemoveProp);
                    }
                    else
                    {
                        if (MergeManager.Instance.GetAllPlaceCity().Count<=0)
                        {
                            UIManager.Instance.GetWindow<UIMsgTips>().ShowMsg("暂无可选择的房子!");
                        }
                        else
                        {
                            UIManager.Instance.GetWindow<UsePropItemMask>().Open(UsePropTypes.Remove);
                        }
                    }
                    
                    clickTime = 0;
                    break;
                case "BtnRefreshCity":
                    if (clickTime < 0.5f) return;
                    clickTime = 0;
                    if (DataManager.Instance.GetPropNum(PropId.RefreshProp) <= 0)
                    {
                        ShowReceivePropUI(PropId.RefreshProp);
                    }
                    else
                    {
                        MergeManager.Instance.ResetCityUnitQueue();
                    }
                    break;
                case "BtnMoveCity":
                    if (clickTime < 0.5f) return;
                    
                    if (DataManager.Instance.GetPropNum(PropId.MoveProp) < 0)
                    {
                        ShowReceivePropUI(PropId.MoveProp);
                    }
                    else
                    {
                        if (MergeManager.Instance.GetAllPlaceCity().Count<=0)
                        {
                            UIManager.Instance.GetWindow<UIMsgTips>().ShowMsg("暂无可选择的房子!");
                        }
                        else
                        {
                            UIManager.Instance.GetWindow<UsePropItemMask>().Open(UsePropTypes.Move);
                        }
                    }
                    clickTime = 0;
                    break;
                case "BtnSetting":
                    UIManager.Instance.GetWindow<UISetting>().Open();
                    break;
                case "BtnAchievement":
                    UIManager.Instance.GetWindow<UIAchievement>().Open();
                    break;
            }

        }


        void ShowReceivePropUI(int id)
        {
            if (DataManager.Instance.GetPropDayUseNum(id) >=  GameCfg.LimitDayUsePropNum)
            {
                UIManager.Instance.GetWindow<UIMsgTips>().ShowMsg("今日获取次数已用完，请明日再来！");
            }
            else
            {
                UIManager.Instance.GetWindow<UIReceivePropTips>().Open(id);
            }
        }


        //刷新道具
        void OnRefreshPropNum()
        {
            List<PropItem> propItems = DataManager.Instance.PropItems;

            for (int i = 0; i < propItems.Count; i++)
            {
                PropItem item = propItems[i];
                switch (item.Id)
                {
                    case PropId.RefreshProp:
                        refreshNumTxt.text = item.Num.ToString();
                        refreshSwitch.index = item.Num > 0 ? 1 : 0;
                        break;
                    case PropId.RemoveProp:
                        clearNumTxt.text = item.Num.ToString();
                        clearSwitch.index = item.Num > 0 ? 1 : 0;
                        break;
                    case PropId.DiscardProp:
                        discardTxt.text = item.Num.ToString();
                        discardSwitch.index = item.Num > 0 ? 1 : 0;
                        break;
                    case PropId.MoveProp:
                        moveNumTxt.text = item.Num.ToString();
                        moveSwitch.index = item.Num > 0 ? 1 : 0;
                        break;
                }
            }
        }

        //刷新积分
        public void OnRefreshScore()
        {
            MergeManager mergeManager = MergeManager.Instance;

            int t = (int) Mathf.Floor(TableConfig.Instance.GetNumericalCfg(DataManager.Instance.Lv).addScore);

            int targetScore = mergeManager.NumericalCfg.addScore;
            int cScore = DataManager.Instance.CurrentScore;


            float fillValue = (cScore - t) / (0.0f + (targetScore - t));

            scoreFill.DOKill();
            scoreFill.DOFillAmount(fillValue, 0.15F);

            scoreTxt.targetValue = cScore;


            bool isShowAddTips = false;
            for (int i = 0; i < showAddInfo.Count; i++)
            {
                if (fillValue >= showAddInfo[i].start && fillValue <= showAddInfo[i].end && showAddTipsNode != i)
                {
                    isShowAddTips = true;
                    showAddTipsNode = i;
                }
            }
            if (isShowAddTips && !addTBuildTips.gameObject.activeSelf)
            {
                addTBuildTips.gameObject.SetActive(true);
                CommonFun.DelayCallback(() => { addTBuildTips.gameObject.SetActive(false); }, 2).Forget();
            }

            //判断是否通关
            if (cScore >= targetScore)
                starEffect.Play();
        }

        //刷新游戏ui显示状态
        public void OnRefreshGameTipsUi()
        {
            showAddTipsNode = -1;
            DataManager dataMgr = DataManager.Instance;
            int lv = dataMgr.Lv;
            oldLvTxt.text = lv.ToString();
            newLvTxt.text = (lv + 1).ToString();
            
        

            int startIndex = 3;
            int addIndex = (int) MathF.Floor(lv / 10);
            int endIndex = startIndex + 2 + addIndex;
            showAddBuildTxt.text = string.Format("下个等级，增加{0}-{1}层", startIndex, endIndex);

            int fNum = TableConfig.Instance.GetFinishedTargetNum(dataMgr.AchievementFinishIndex);
            
            allFinishAchievementNumTxt.text = string.Format("<color=#FFEB3B>{0}</color>/{1}",fNum,TableConfig.Instance.CityTargetCfgList.Count);
            OnRefreshScore();
        }

        public void RefreshBuildMainCityNum(bool isShowAddTips = true)
        {
            DataManager dataMgr = DataManager.Instance;
            mainCityAddNumTips.text =
                string.Format("+{0}", dataMgr.BuildCityIdList.Count - cityTotalNumTxt.targetValue);
            
            cityTotalNumTxt.targetValue = dataMgr.BuildCityIdList.Count;
            
            if (isShowAddTips)
            {
                mainCityAddNumTips.gameObject.SetActive(true);
            
                DOTween.Kill(mainCityAddNumTips.GetInstanceID());
                mainCityAddNumTips.transform.localPosition = new Vector3(40, 0, 0);
                Sequence sq = DOTween.Sequence().SetId(mainCityAddNumTips.GetInstanceID());

                sq.Append(mainCityAddNumTips.transform.DOLocalMoveY(100, 2F));
                sq.OnComplete(() =>
                {
                    mainCityAddNumTips.gameObject.SetActive(false);
                });
            }
        }


        public Vector3[] GetScoreFillPos(Vector3 startPos)
        {
            Vector3[] path = new Vector3[3];
            path[0] = startPos;
            path[2] = GetScoreFillWorldPoint();
            path[1] = (path[0] + path[2]) / 2f + new Vector3(UnityEngine.Random.Range(-5, 5),
                UnityEngine.Random.Range(0, 30), UnityEngine.Random.Range(-30, 0));
            return path;
        }

        //获取进度条位置
        public Vector3 GetScoreFillWorldPoint()
        {
            float f = scoreFill.fillAmount;
            float width = scoreFill.sprite.textureRect.size.x;
            //开始点
            float x = ((Screen.width / 2) - (width / 2)) + (f * width);
            Vector3 pos = new Vector3(x,
                Screen.height / 2 + this.transform.InverseTransformPoint(scoreFill.transform.position).y, 0);
            //文本坐标
            return PositionConvert.ScreenPointToWorldPoint(PositionConvert.UIPointToScreenPointOverlay(pos),
                Math.Abs(GameCameraControl.I.transform.position.z));
        }

        //获取进度条位置
        public Vector3 GetScoreFillUIPoint()
        {
            float f = scoreFill.fillAmount;
            float width = scoreFill.sprite.textureRect.size.x;
            //开始点
            float x = -(width / 2) + (f * width);
            return new Vector3(x, this.transform.InverseTransformPoint(scoreFill.transform.position).y, 0);
        }
    }
}

